/**
 * related to listview_cell.ui
 * 
 * @Author : and
 * @Timestamp : 2016-10-05
 */
// require
var core = require("do/core");
var page = require("do/page");
// sm
var do_DataCache = sm("do_DataCache");
var do_Page = sm("do_Page");
var do_App = sm("do_App");
// mm
var do_ListData = mm("do_ListData");
// ui
var root = ui('$');
var _topic;
var listview = ui('listview');
var current_page = 0;
var getdata;
// init
(function() {
	root.setMapping({
		"listview.tag" : "tag"
	})
	listview.bindItems(do_ListData);
})();

// event
listview.on("touch", function(index) {
	var d = do_ListData.getOne(index);
	do_App.openPage({
		source: "source://view/todoReceipt/tododetail/tododetail.ui",
		statusBarState: "transparent",
		animationType: "push_r2l",
		data: {detaildata : getdata[index],
			type : _topic
		}
	});
});
listview.on("scroll", function(position) {
	if (position.lastVisiblePosition == current_page * 10) {
		fetchdata(++current_page);
	}
})
do_Page.on("indexChanged", function(topic) {
	core.p(topic)
	_topic = listview.tag;
	if (_topic == topic && current_page == 0) {
		fetchdata(++current_page);
	}
})
// private function
function fetchdata(num) {
	var topic = listview.tag;
	var url = "?page=" + num + "&limit=10";
	core.p("topic"+topic);
	if (topic == "GetAllFinishWork") {
		url = url + "&tab=" + topic;
		url = do_DataCache.loadData("baseUrl") + topic + "";
	} else {
		core.p("loginer" + do_DataCache.loadData("loginer").returnObj[0].User_id)
		url = do_DataCache.loadData("baseUrl") + topic + "?User_id=" + do_DataCache.loadData("loginer").returnObj[0].User_id;
		core.p("url" + url)
	}
	
	
	if (num == 1)
				page.showView("source://script/do/view/waitting.ui");
	var http = mm("do_Http");
	http.method = "GET";
	http.timeout = 10000;
	http.contentType = "application/x-www-form-urlencoded";
	http.url = url
	deviceone.print(http.url);
	http.on("success", function(data, e) {
		var jsonString = data.replace("<?xml version=\"1.0\" encoding=\"utf-8\"?>\r\n<string xmlns=\"http://tempuri.org/\">","");
		jsonString = jsonString.replace("</string>","");
		core.p(jsonString);
		var bean = JSON.parse(jsonString);
		deviceone.print(bean.result);
		if (bean.result==200) {
			if (num == 1)
				do_ListData.removeAll();
			else {
				do_ListData.removeData([ do_ListData.getCount() - 1 ]);
			}
			do_ListData.addData(bean.returnObj);
			getdata = bean.returnObj;
			var next = {};
			next.template = 1;
			do_ListData.addOne(next);
			// core.p(do_ListData);
			listview.refreshItems();
			
		}else {
			core.toast(bean.msg);
		}
		page.hideView("source://script/do/view/waitting.ui");
	});
	http.on("fail", function(data, e) {
		deviceone.print(JSON.stringify(data));
		if (data.status == 404) {
			core.toast("用户名或密码错误");
		} else {
			core.toast("网络问题");
		}
		progressBar.visible = false;
		
	});
	http.request();
	
}